﻿var me = this,
    draftId = PAI.Global.getUrlData('draftId'),
    controller = this.lookupController(),
    vm = this.lookupViewModel(),
    checkIsNull = function (currentData, fields, msgTpl, grid, otherLogic) {
        //先获取到grid的所有列
        var gridColumns = grid.getColumnManager().columns;

        for (var key in currentData) {
            if (Ext.Array.contains(fields, key)) {
                //获取Key 对应的列明. (可能存在列名和字段名不一致的情况. 提示信息最好显示成列名.)
                var columnText = '';
                var currentColumn = gridColumns.filter((r) => {
                    return r.dataIndex == key;
                })[0];

                if (currentColumn) {
                    columnText = currentColumn.text;
                }

                if ((key == 'Quantity' || key == 'UnitPrice' || key == 'TotalPrice') && currentData[key] == 0) {
                    return [Ext.String.format(msgTpl, columnText)];
                } else if ((currentData[key] == "" && currentData[key] !== 0) || currentData[key] == undefined || currentData[key] == null) {
                    return [Ext.String.format(msgTpl, columnText)];
                }

                //如果还有其他的逻辑判断,则执行.
                if (otherLogic) {
                    var cmpErrors = otherLogic(currentData);
                    if (!Ext.isEmpty(cmpErrors)) {
                        return [cmpErrors];
                    }
                }
            }
        }
    };

controller.balance = controller.balance || {};
controller.budgetControl = controller.budgetControl || {};

var expenseType = ref.ExpenseType.getValue();
var grid1 = ref.datagrid1;
var grid2 = ref.datagrid2;
var grid3 = ref.datagrid3;
var grid4 = ref.datagrid4;
var grid5 = ref.datagrid5;

var viewStatus = vm.get('NebulogyForm.companySection.status');

var store2 = grid2.getStore();

var purStore = store2;

//自定义版块错误提示通用方法
//cmp：需检测组件
//getCmpErrors（cmp）：回调函数，返回自定义组件错误信息
//     有错误返回数组，无错误不返回数据
//scope: 回调函数作用域（getCmpErrors）
function customVerification(cmp, getCmpErrors, scope) {
    var block = cmp.up('[isPaiFormBlock]'), //组件所属版块
        cmpErrors = getCmpErrors.call(scope || this, cmp),
        cmpName = cmp.compDisplay || cmp.name; //需检测自定义错误的组件

    if (block) {
        if (!block.activeErrors)
            block.activeErrors = {};

        delete block.activeErrors[cmpName]; //删除上次错误提示
        if (!Ext.isEmpty(cmpErrors)) { //错误不为空，则添加错误提示
            errors.push(cmpErrors);
            block.activeErrors[cmpName] = cmpErrors;
        }
        block.updateActiveErrors();
    }
    return cmpErrors;
}

if (action == 'PA_ReturnOriginator' || action == 'PA_ReturnOriginatorSelfExBack' || action == 'Enquiry') {
    return true;
}

if (me.analysis.status == 'launch' || me.analysis.status == 'resubmit') {
    //GL Account不能为空
    customVerification(ref.Account, function (cmp) {
        if (cmp.getValue() == null || cmp.getValue().match(/^[ ]*$/)) {
            return ['Account information is missing in the General Information part.'];
        }
    }, this);

    //Attachments附件必填
    customVerification(ref.file8, function (cmp) {
        if (cmp.store.getCount() == 0) {
            cmp.compDisplay = 'Attachments';
            return ['Please upload your attachment'];
        }
    }, this);

    //Vendor Information 必填
    customVerification(ref.datagrid1, function (cmp) {
        cmp.compDisplay = 'Vendor Information';
        if (cmp.store.data.items.length > 0) {
            for (var i = 0; i < cmp.store.data.items.length; i++) {
                var name = cmp.store.data.items[i].data.Name || '';
                if (!name.trim()) {
                    return ['Vendor Name is missing in the Vendor Information.'];
                }
            }
        } else {
            return ['Please fill in Vendor Information.'];
        }
    }, this);

    //Purchase Items 表格必填字段校验
    customVerification(grid2, function (cmp) {
        cmp.compDisplay = cmp.up().title;

        if (cmp.store.data.items.length > 0) {
            var fields = ['DescriptionOfSuppliesServices', 'ProjectActivity', 'DeliveryDateStart', 'DeliveryDateEnd', 'MaterialGroup', 'Quantity', 'UnitPrice', 'TaxRate'];
            var msgTpl = 'Please fill in the the blank field: {0} in Purchase Items section.';

            for (var i = 0; i < cmp.store.data.items.length; i++) {
                var currentData = cmp.store.data.items[i].data;

                var returnValue = checkIsNull(currentData, fields, msgTpl, cmp, function (r) {
                    //NewReplaceTransfer选择了Replac. VINIf则必填.
                    if (r.NewReplaceTransfer == '2' && !r.VINIf) {
                        return [Ext.String.format(msgTpl, 'VINIf')];
                    }
                });

                if (!Ext.isEmpty(returnValue)) {
                    return returnValue;
                }
            }
        } else {
            return ['Please fill in Purchase Items.'];
        }
    }, this);

    var uKCrossCharge = ref.UKCrossCharge.getValue();
    if (uKCrossCharge == 'JLRCUK' || uKCrossCharge == 'UKJLRC' || uKCrossCharge == 'No') {

        customVerification(ref.file7, function (cmp) {
            cmp.compDisplay = cmp.up().title;
            if (uKCrossCharge != 'No') {
                if (cmp.store.getCount() == 0) {
                    return ['Please upload your UK Cross Charge Attachments. '];
                }
            }
        });

        customVerification(grid3, function (cmp) {
            //Company Allocation 提交非空验证
            var _store = cmp.getStore();
            cmp.compDisplay = cmp.up().title;

            if (uKCrossCharge == "UKJLRC" || uKCrossCharge == "No") {
                //判断列表是否为空
                if (_store.data.items.length > 0) {
                    var fields = ['DescriptionOfSuppliesServices', 'ProjectActivity', 'Company', 'CompanySharingRatio', 'Cost'];
                    var msgTpl = 'Please fill in the the blank field: {0} in the Company Allocation section.';

                    var companyList = [];
                    for (var i = 0; i < _store.data.items.length; i++) {
                        var currentData = _store.data.items[i].data;

                        companyList.push(currentData['Company']);
                        var returnValue = checkIsNull(currentData, fields, msgTpl, grid3);

                        if (!Ext.isEmpty(returnValue)) {
                            return returnValue;
                        }
                    }
                }
                else {
                    return ['Please fill in Company Allocation Information.'];
                }

                //需要对Company Allocation中相同的 Desceiption,ProjectActivity的 CompanySharingRatio 作100%判断.
                var sameObj = {};
                //Company Allocation 子表必须与Purchase Items 中 数量相等.
                var arr = [];
                //判断是否包含JLRC
                var hasJLRC = false;

                Ext.each(_store.data.items, function (record) {
                    var key = Ext.String.format('{0}_{1}', record.get('DescriptionOfSuppliesServices'), record.get('ProjectActivity'));
                    //相同的 Description + ProjectActivity,就把CompanySharingRatio相加
                    /* 结构如下,相同的Description + ProjectActivity 必须等于100.
                        {
                            value_value1: 100,
                            value_value2: 90,
                        }
                     */
                    if (!sameObj[key]) {
                        sameObj[key] = record.get('CompanySharingRatio');
                    } else {
                        sameObj[key] += record.get('CompanySharingRatio');
                    }

                    if (!Ext.Array.contains(arr, key)) {
                        arr.push(key);
                    }

                    if (!hasJLRC) {
                        hasJLRC = record.get('Company') == 'JLRC';
                    }
                });
                for (var k in sameObj) {
                    if (sameObj[k] != 100) {
                        return ['Sum of Project Activity sharing ratio must be equal to 100% in the Company Allocation section.'];
                    }
                }

                if (arr.length != purStore.data.items.length) {
                    return ['Please ensure all Company Allocation items have been allocated according to Purchase Items.'];
                }

                var companyValue = ref.companyC.getValue();
                if (!hasJLRC && companyValue == 'JLRC') {
                    return ['Company Allocation: Data for company = JLRC must be included.'];
                }

                //判断CompanyAllocation表格中，是否存在balance
                //前提：ExpenseType的值为FME或SE, 对JLRC的balance做卡控,以ProjectActivity为维度统计总Cost.
                var expenseTypeArr = ['1', '2', '3', '6'];

                if (!controller.isInquiryCall) {
                    controller.isInquiryCall = vm.get('NebulogyForm.isInquiryCall') || 0;
                }

                if (expenseTypeArr.includes(expenseType) && controller.isInquiryCall == 0 && companyValue == 'JLRC') {
                    var companyCost = {};

                    Ext.each(_store.data.items, function (record) {
                        if (record.get('budgetControl') == 'Y' && record.get('Company') == 'JLRC') {
                            var key = record.get('ProjectActivity');
                            controller.getBalance(key);

                            if (!companyCost[key]) {
                                companyCost[key] = record.get('Cost');
                            } else {
                                companyCost[key] = parseFloat((companyCost[key] + record.get('Cost')).toFixed(2));
                            }
                        }
                    });

                    for (var pa in companyCost) {
                        if (companyCost[pa] > controller.balance[pa]) {
                            return [Ext.String.format('The Total Cost of {0} Cannot be Greater Than The Corresponding Balance: {1}', pa, controller.balance[pa])];
                        }
                    }
                }
            }
        });

        customVerification(grid4, function (cmp) {
            var _store = cmp.getStore();
            var parentSection = cmp.up();
            cmp.compDisplay = parentSection.title;

            if (!parentSection.hidden) {
                if (_store.data.items.length > 0) {
                    var fields = ['DescriptionOfSuppliesServices', 'ProjectActivity', 'JASharingRatio', 'JACost', 'JACostCenter', 'LRSharingRatio', 'LRCost', 'LRCostCenter'];

                    for (var i = 0; i < _store.data.items.length; i++) {
                        var currentData = _store.data.items[i].data,
                            msg;

                        for (var key in currentData) {
                            if (Ext.Array.contains(fields, key)) {
                                if (currentData.JASharingRatio + currentData.LRSharingRatio != 100) {
                                    return ['JASharingRatio plus LRSharingRatio has to equal 100%！'];
                                }
                                else if (currentData[key] === "" || currentData[key] == undefined || currentData[key] == null) {
                                    return ['Please fill in the the blank field: {0} in the Brand Allocation(JLRC) section.'];
                                }
                            }
                        }
                    }

                    if (uKCrossCharge == 'No' || uKCrossCharge == 'UKJLRC') {
                        //Brand Allocation(JLRC) 子表必须与Company Allocation 中 Company=JLRC的 数量相等.
                        var arr = [];
                        var store3 = ref.datagrid3.getStore();
                        Ext.each(store3.data.items, function (r) {
                            var key = Ext.String.format('{0}_{1}_{2}', r.get('DescriptionOfSuppliesServices'), r.get('ProjectActivity'), r.get('Company'));
                            if (!Ext.Array.contains(arr, key) && r.get('Company') == 'JLRC') {
                                arr.push(key);
                            }
                        });

                        if (arr.length != _store.data.items.length) {
                            return ['Please ensure all JLRC budget items have been allocated according to JA&LR brand.'];
                        }
                    } else if (uKCrossCharge == 'JLRCUK') {
                        //Brand Allocation(JLRC) 子表必须与Purchase Items  数量相等.
                        var arr = [];
                        Ext.each(purStore.data.items, function (r) {
                            var key = Ext.String.format('{0}_{1}', r.get('DescriptionOfSuppliesServices'), r.get('ProjectActivity'));
                            if (!Ext.Array.contains(arr, key)) {
                                arr.push(key);
                            }
                        });

                        if (arr.length != _store.data.items.length) {
                            return ['Please ensure all JLRC budget items have been allocated according to JA&LR brand.'];
                        }
                    }
                }
                else {
                    return ['Please fill in Brand Allocation(JLRC) Information.'];
                }
            }
        });

        if (uKCrossCharge == 'UKJLRC' || uKCrossCharge == 'No') {
            customVerification(grid5, function (cmp) {
                var _store = cmp.getStore();
                var parentSection = cmp.up();
                cmp.compDisplay = parentSection.title;

                if (!parentSection.hidden) {
                    if (_store.data.items.length > 0) {
                        var fields = ['DescriptionOfSuppliesServices', 'ProjectActivity', 'JASharingRatio', 'JACost', 'JAWBS', 'LRSharingRatio', 'LRCost', 'LRWBS', 'CostCenter'];

                        for (var i = 0; i < _store.data.items.length; i++) {
                            var currentData = _store.data.items[i].data;

                            for (var key in currentData) {
                                if (Ext.Array.contains(fields, key)) {
                                    if (currentData.JASharingRatio + currentData.LRSharingRatio != 100) {
                                        return ['JASharingRatio plus LRSharingRatio has to equal 100%！'];
                                    }
                                    else if (currentData[key] === "" || currentData[key] == undefined || currentData[key] == null) {
                                        return ['Please fill in the the blank field: {0} in the Brand Allocation(JLRC) section.'];
                                    }
                                }
                            }
                        }

                        //Brand Allocation(JLRC) 子表必须与Company Allocation 中 Company=JLRC的 数量相等.
                        var arr = [];
                        var store3 = ref.datagrid3.getStore();
                        Ext.each(store3.data.items, function (r) {
                            var key = Ext.String.format('{0}_{1}_{2}', r.get('DescriptionOfSuppliesServices'), r.get('ProjectActivity'), r.get('Company'));
                            if (!Ext.Array.contains(arr, key) && r.get('Company') == 'CJLR') {
                                arr.push(key);
                            }
                        });

                        if (arr.length != _store.data.items.length) {
                            return ['Please ensure all CJLR budget items have been allocated according to JA&LR brand.'];
                        }
                    }
                    else {
                        return ['Please fill in Brand Allocation(CJLR) Information.'];
                    }
                }
            });

        }
    }

    if (requestData.bizModel.CompanyAllocation) {

        Ext.each(requestData.bizModel.CompanyAllocation, function (rr) {
            var pa = rr.ProjectActivity;

            if (rr.Company == 'JLRC') {
                rr.Balance = controller.balance[pa];
            }
        });
    }
} else if (viewStatus == 'approval') {
    var activity = vm.get('NebulogyForm.companySection.activity');


}

customVerification(ref.approverDesc, function (cmp) {
    cmp.compDisplay = 'Comment';
    if (cmp.notBlank) {
        if (!cmp.getValue() || !cmp.getValue().trim()) {
            return ['Please enter your Comment !'];
        }
    }
});

return errors.length == 0;